package com.lhs.Timer;

import com.lhs.config.redis.ZiDeRedisUtil;
import com.lhs.mapper.blog_likeMapper;
import com.lhs.mapper.blog_post_0Mapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class DataSyncScheduler {

    @Autowired
    private ZiDeRedisUtil ziDeRedisUtil;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private blog_likeMapper blogLikeMapper;
    @Autowired
    private blog_post_0Mapper blogPostMapper;

    /**
     * 每5分钟同步一次点赞数据[1](@ref)
     */
    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void syncLikeData() {
        log.info("开始同步点赞数据...");

        // 获取所有点赞数Key

        Collection<String> likeCountKeys = ziDeRedisUtil.keys("blog:like:count:*");

        for (String key : likeCountKeys) {
            try {
                // 提取postId
                Long postId = Long.parseLong(key.substring(key.lastIndexOf(":") + 1));

                // 获取Redis中的点赞数
                Long likeCount = ziDeRedisUtil.getCacheObject(key);
                if (likeCount != null) {
                    // 使用分布式锁保证数据同步安全
                    String lockKey = "lock:sync:like:" + postId;
                    RLock lock = redissonClient.getLock(lockKey);

                    try {
                        if (lock.tryLock(3, 10, TimeUnit.SECONDS)) {
                            // 更新数据库
                            blogPostMapper.updateLikeCount(postId, likeCount);
                            log.debug("同步文章{}点赞数: {}", postId, likeCount);
                        }
                    } finally {
                        if (lock.isHeldByCurrentThread()) {
                            lock.unlock();
                        }
                    }
                }
            } catch (Exception e) {
                log.error("同步点赞数据失败，key: {}", key, e);
            }
        }

        log.info("点赞数据同步完成");
    }

    /**
     * 每10分钟同步一次浏览数据
     */
    @Scheduled(fixedRate = 10 * 60 * 1000)
    public void syncViewData() {
        log.info("开始同步浏览数据...");

        // 获取所有浏览数Key
        Collection<String> viewCountKeys = ziDeRedisUtil.keys("blog:view:count:*");

        for (String key : viewCountKeys) {
            try {
                // 提取postId
                Long postId = Long.parseLong(key.substring(key.lastIndexOf(":") + 1));

                // 获取Redis中的浏览数
                Long viewCount = ziDeRedisUtil.getCacheObject(key);
                if (viewCount != null) {
                    // 使用分布式锁保证数据同步安全
                    String lockKey = "lock:sync:view:" + postId;
                    RLock lock = redissonClient.getLock(lockKey);

                    try {
                        if (lock.tryLock(3, 10, TimeUnit.SECONDS)) {
                            // 更新数据库
                            blogPostMapper.updateViewCount(postId, viewCount);
                            log.debug("同步文章{}浏览数: {}", postId, viewCount);
                        }
                    } finally {
                        if (lock.isHeldByCurrentThread()) {
                            lock.unlock();
                        }
                    }
                }
            } catch (Exception e) {
                log.error("同步浏览数据失败，key: {}", key, e);
            }
        }

        log.info("浏览数据同步完成");
    }
}